// 引入axios**
import axios from 'axios';
import VueCookies from 'vue-cookies'

//获取token的方法
function getTokenByLocal() {
    // 线上环境
    // 09bcbf2b-1806-11eb-bf0c-506b4bff3204
    let hesytoken = getCookie('hesytoken') || '7662a1a6-ef3e-11eb-ba9a-506b8d76caa6';
    return hesytoken;
    // getCookie('hesytoken')

    // 本地测试
    // let hesytoken = getCookie.getItem('token') || '';
    // 
    return hesytoken
}
// 测试环境截取token
// function getCookie(cname) {
//     let token=document.cookie
//     // let token='hesytoken=f09dc75c-1e3f-11eb-91ff-0a0027000009'
//     let post='token='
//     var i=token.indexOf(post)
//     if(i>=0){
//         console.log(token.substring(i+post.length))
//         token=token.substring(i+post.length,token.length)
//         return token
//     }else{
//         return ''
//     }
// }
// 生产环境截取token
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

//创建一个axios实例**
const service = axios.create({
    timeout: 5000    //请求超时时间
})
//设置request请求拦截器**
service.interceptors.request.use(
    config => {
        if (getTokenByLocal()) {
            config.headers['hesytoken'] = getTokenByLocal();        //让每个请求携带自定义的token
            // config.headers['ContentType'] = 'application/from-data;charset=utf-8'    //后台接收参数的类型
        }
        return config
    },
    error => {
        Promise.reject(error)
    }
)

//response响应拦截器**
service.interceptors.response.use(
    response => {
        let res = response;
        return Promise.resolve(response)
    },
    error => {
        //这里可以进行提示 或者弹窗
        return Promise.reject(error);
    }
)
//导出这个方法
export default service
